<template>
  <div class="realtime-waveform-page">
    <el-card class="page-header">
      <div slot="header" class="header-content">
        <div class="title-section">
          <h2>实时加速度波形监控</h2>
          <div class="device-info">
            <el-tag type="info">设备ID: {{ deviceId }}</el-tag>
            <el-tag v-if="currentSensor" type="success">传感器: {{ currentSensor }}</el-tag>
          </div>
        </div>
        
        <div class="control-section">
          <websocket-status />
          <el-button @click="goBack" icon="el-icon-back">返回</el-button>
        </div>
      </div>
    </el-card>
    
    <el-row :gutter="20">
      <!-- 左侧控制面板 -->
      <el-col :span="6">
        <el-card>
          <div slot="header">控制面板</div>
          
          <!-- 设备选择 -->
          <div class="control-group">
            <h4>设备选择</h4>
            <el-select v-model="selectedDeviceId" @change="handleDeviceChange" placeholder="选择设备">
              <el-option
                v-for="device in deviceList"
                :key="device.id"
                :label="`${device.name} (${device.id})`"
                :value="device.id">
              </el-option>
            </el-select>
          </div>
          
          <!-- 传感器选择 -->
          <div class="control-group">
            <h4>传感器选择</h4>
            <el-select v-model="selectedSensor" @change="handleSensorChange" placeholder="选择传感器">
              <el-option label="全部传感器" value=""></el-option>
              <el-option
                v-for="sensor in sensorList"
                :key="sensor"
                :label="sensor"
                :value="sensor">
              </el-option>
            </el-select>
          </div>
          
          <!-- 窗口设置 -->
          <div class="control-group">
            <h4>时间窗口</h4>
            <el-slider
              v-model="windowSize"
              :min="30"
              :max="300"
              :step="30"
              :format-tooltip="formatTooltip"
              @change="handleWindowSizeChange">
            </el-slider>
            <div class="slider-labels">
              <span>30秒</span>
              <span>5分钟</span>
            </div>
          </div>
          
          <!-- 数据类型选择 -->
          <div class="control-group">
            <h4>数据类型</h4>
            <el-radio-group v-model="dataType" @change="handleDataTypeChange">
              <el-radio label="rms">均方根(RMS)</el-radio>
              <el-radio label="peak">峰值(Peak)</el-radio>
            </el-radio-group>
          </div>
          
          <!-- 阈值设置 -->
          <div class="control-group">
            <h4>阈值设置</h4>
            <div class="threshold-item">
              <label>X轴阈值:</label>
              <el-input-number
                v-model="thresholds.x"
                :precision="2"
                :step="0.1"
                :min="0"
                size="small">
              </el-input-number>
            </div>
            <div class="threshold-item">
              <label>Y轴阈值:</label>
              <el-input-number
                v-model="thresholds.y"
                :precision="2"
                :step="0.1"
                :min="0"
                size="small">
              </el-input-number>
            </div>
            <div class="threshold-item">
              <label>Z轴阈值:</label>
              <el-input-number
                v-model="thresholds.z"
                :precision="2"
                :step="0.1"
                :min="0"
                size="small">
              </el-input-number>
            </div>
          </div>
          
          <!-- 统计信息 -->
          <div class="control-group">
            <h4>统计信息</h4>
            <div class="stats-grid">
              <div class="stat-item">
                <span class="label">数据点数:</span>
                <span class="value">{{ stats.dataPoints }}</span>
              </div>
              <div class="stat-item">
                <span class="label">更新频率:</span>
                <span class="value">{{ stats.frequency }}Hz</span>
              </div>
              <div class="stat-item">
                <span class="label">延迟:</span>
                <span class="value">{{ stats.latency }}ms</span>
              </div>
              <div class="stat-item">
                <span class="label">内存使用:</span>
                <span class="value">{{ formatBytes(stats.memory) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧波形图 -->
      <el-col :span="18">
        <el-card>
          <div slot="header" class="chart-header">
            <span>实时波形图</span>
            <div class="chart-controls">
              <el-button-group size="small">
                <el-button 
                  :type="isActive ? 'danger' : 'success'" 
                  @click="toggleRealtime"
                  :icon="isActive ? 'el-icon-video-pause' : 'el-icon-video-play'"
                  :disabled="!isWebSocketConnected"
                >
                  {{ isActive ? '暂停' : '开始' }}
                </el-button>
                <el-button @click="clearData" icon="el-icon-delete">清空</el-button>
                <el-button @click="resetZoom" icon="el-icon-refresh-left">重置</el-button>
                <el-button @click="exportData" icon="el-icon-download">导出</el-button>
              </el-button-group>
            </div>
          </div>
          
          <div class="chart-content">
            <realtime-waveform
              ref="realtimeChart"
              :device-id="deviceId"
              :sensor-id="currentSensor"
              :window-size="windowSize"
              :max-data-points="maxDataPoints"
              @stats-update="handleStatsUpdate"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import RealtimeWaveform from '@/components/RealtimeWaveform'
import WebSocketStatus from '@/components/WebSocketStatus'

export default {
  name: 'RealtimeWaveformPage',
  components: {
    RealtimeWaveform,
    WebSocketStatus
  },
  data() {
    return {
      // 设备相关
      selectedDeviceId: null,
      deviceList: [],
      
      // 传感器相关
      selectedSensor: '',
      sensorList: ['传感器1', '传感器2', '传感器3'],
      
      // 配置参数
      windowSize: 60,
      maxDataPoints: 1000,
      dataType: 'rms',
      
      // 阈值设置
      thresholds: {
        x: 1.0,
        y: 1.0,
        z: 1.0
      },
      
      // 状态
      isActive: false,
      
      // 统计信息
      stats: {
        dataPoints: 0,
        frequency: 0,
        latency: 0,
        memory: 0
      }
    }
  },
  computed: {
    ...mapGetters('websocket', ['connectionInfo']),
    
    deviceId() {
      return this.$route.query.deviceId || this.selectedDeviceId
    },
    
    currentSensor() {
      return this.selectedSensor
    },
    
    isWebSocketConnected() {
      return this.connectionInfo.isConnected
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    /**
     * 初始化页面
     */
    async initPage() {
      // 从路由参数获取设备ID
      if (this.$route.query.deviceId) {
        this.selectedDeviceId = this.$route.query.deviceId
      }
      
      // 加载设备列表
      await this.loadDeviceList()
      
      // 初始化WebSocket连接
      if (!this.isWebSocketConnected) {
        await this.$store.dispatch('websocket/initWebSocket')
      }
    },
    
    /**
     * 加载设备列表
     */
    async loadDeviceList() {
      try {
        // 这里调用API获取设备列表
        // const response = await getDeviceList()
        // this.deviceList = response.data
        
        // 模拟数据
        this.deviceList = [
          { id: '30096546', name: '设备A' },
          { id: '30096547', name: '设备B' },
          { id: '30096548', name: '设备C' }
        ]
      } catch (error) {
        console.error('加载设备列表失败:', error)
      }
    },
    
    /**
     * 处理设备变化
     */
    handleDeviceChange(deviceId) {
      this.selectedDeviceId = deviceId
      // 更新路由参数
      this.$router.replace({
        query: { ...this.$route.query, deviceId }
      })
    },
    
    /**
     * 处理传感器变化
     */
    handleSensorChange(sensor) {
      this.selectedSensor = sensor
    },
    
    /**
     * 处理窗口大小变化
     */
    handleWindowSizeChange(size) {
      this.windowSize = size
    },
    
    /**
     * 处理数据类型变化
     */
    handleDataTypeChange(type) {
      this.dataType = type
    },
    
    /**
     * 切换实时状态
     */
    toggleRealtime() {
      if (this.$refs.realtimeChart) {
        this.$refs.realtimeChart.toggleRealtime()
        this.isActive = !this.isActive
      }
    },
    
    /**
     * 清空数据
     */
    clearData() {
      if (this.$refs.realtimeChart) {
        this.$refs.realtimeChart.clearChart()
      }
    },
    
    /**
     * 重置缩放
     */
    resetZoom() {
      if (this.$refs.realtimeChart) {
        this.$refs.realtimeChart.resetZoom()
      }
    },
    
    /**
     * 导出数据
     */
    exportData() {
      // 实现数据导出功能
      this.$message.info('导出功能开发中...')
    },
    
    /**
     * 处理统计信息更新
     */
    handleStatsUpdate(newStats) {
      this.stats = { ...newStats }
    },
    
    /**
     * 格式化提示
     */
    formatTooltip(value) {
      return `${value}秒`
    },
    
    /**
     * 格式化字节数
     */
    formatBytes(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    
    /**
     * 返回上一页
     */
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
.realtime-waveform-page {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title-section {
        h2 {
          margin: 0 0 8px 0;
          color: #303133;
        }
        
        .device-info {
          .el-tag {
            margin-right: 8px;
          }
        }
      }
      
      .control-section {
        display: flex;
        align-items: center;
        gap: 16px;
      }
    }
  }
  
  .control-group {
    margin-bottom: 24px;
    
    h4 {
      margin: 0 0 12px 0;
      color: #606266;
      font-size: 14px;
      font-weight: 500;
    }
    
    .el-select {
      width: 100%;
    }
    
    .slider-labels {
      display: flex;
      justify-content: space-between;
      font-size: 12px;
      color: #909399;
      margin-top: 4px;
    }
    
    .threshold-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      
      label {
        font-size: 13px;
        color: #606266;
      }
    }
    
    .stats-grid {
      .stat-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        
        .label {
          font-size: 13px;
          color: #909399;
        }
        
        .value {
          font-size: 13px;
          color: #303133;
          font-weight: 500;
        }
      }
    }
  }
  
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .chart-content {
    height: 600px;
  }
}
</style>
